'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
  /**
   * 设置前端路由
   * @param {*} userModel 用户模型
   */
  async _setWebRouter(userModel) {
    if (userModel) {
      const allPages = await this.service.authPage.all();
      if (userModel.type === 'ADMIN') {
        userModel.pages = allPages;
      } else if (userModel.role) {
        const pageSet = new Set(userModel.role.pages);
        userModel.pages = allPages.filter(item => {
          if (item.children) {
            item.children = item.children.filter(item1 => {
              if (item1.children) {
                item1.children = item1.children.filter(item2 => {
                  return pageSet.has(item2.path);
                });
              }
              return pageSet.has(item1.path);
            });
          }
          return pageSet.has(item.path);
        });
      }
    }
  }
  /**
   * 登录
   */
  async login() {
    this.ctx.validate({
      user: {
        type: 'string',
        trim: true,
        format: /^[0-9A-Za-z]{4,20}$/,
      },
      pass: {
        type: 'string',
        format: /^[0-9A-Za-z]{6,20}$/,
        trim: true,
      },
      code: {
        type: 'string',
        format: /^[0-9A-Za-z]{4}$/,
        trim: true,
      },
    });
    const data = await this.ctx.service.user.login(this.ctx.w_body());
    this.ctx.rotateCsrfSecret();
    await this._setWebRouter(data);
    this.ctx.sendSuccess(data);
  }
  /**
   * 获取用户数据
   */
  async sessionLogin() {
    const data = await this.ctx.service.user.sessionLogin();
    await this._setWebRouter(data);
    this.ctx.sendSuccess(data);
  }

  /**
   * 获取验证码 Verification code
   */
  async verificationCode() {
    this.ctx.service.user.verificationCode();
  }
}

module.exports = UserController;
